package vn.nt.healthcare.server.ws.service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import vn.nt.healthcare.server.ws.domain.Company;
import vn.nt.healthcare.server.ws.model.Services;
import vn.nt.healthcare.server.ws.repositories.CompanyRepository;
import vn.nt.healthcare.server.ws.service.ServicesService;

@Service("servicesService")
@Transactional
public class ServicesServiceImpl implements ServicesService {

	@Autowired
	private CompanyRepository companyRepository;

	@SuppressWarnings("unchecked")
	@Override
	public List<Services> findServices(String company) {
		// TODO Auto-generated method stub
		Company company_ = companyRepository.findByCode(company);
		if (company_ == null) {
			return null;
		} else {
			Session session = null;
			try {
				session = ServiceHelper.openSession(company_);
				StringBuilder sql = new StringBuilder(
						"SELECT DISTINCT s WHERE Services s WHERE 1 = 1");
				Query query = session.createQuery(sql.toString());
				return query.list();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Services> findServicesBySub(String company, int subId) {
		// TODO Auto-generated method stub
		Company company_ = companyRepository.findOne(company);
		if (company_ == null) {
			return null;
		} else {
			Session session = null;
			try {
				session = ServiceHelper.openSession(company_);
				StringBuilder sql = new StringBuilder(
						"SELECT DISTINCT s FROM Services s WHERE s.subject.Id = :subId");
				Query query = session.createQuery(sql.toString());
				query.setInteger("subId", subId);
				return query.list();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return null;
	}

	@Override
	public Services findServiceById(String company, int serviceId) {
		Company company_ = companyRepository.findOne(company);
		if (company_ == null) {
			return null;
		} else {
			Session session = null;
			try {
				session = ServiceHelper.openSession(company_);
				Services s = (Services) session.get(Services.class, serviceId);
				return s;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return null;
	}

}
